package com.xjz.controller;

import cn.hutool.core.io.FileUtil;
import com.xjz.common.BaseResponse;
import com.xjz.common.ResultUtils;
import com.xjz.common.enums.ErrorCode;
import com.xjz.constant.FileConstant;
import com.xjz.exception.BusinessException;
import com.xjz.manager.CosManager;
import com.xjz.model.dto.file.UploadFileRequest;
import com.xjz.model.entity.User;
import com.xjz.model.enums.FileUploadBizEnum;
import com.xjz.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Arrays;
import java.util.List;

/**
 * ClassName: FileController
 * Package: com.xjz.controller
 * Description:
 *
 * @Author 许小健
 * @Create 2025/8/3 10:13
 * @Version 1.0
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Resource
    private UserService userService;

    @Resource
    private CosManager cosManager;

    /**
     * 上传文件
     * @param multipartFile
     * @param uploadFileRequest
     * @param request
     * @return
     */
    @PostMapping("/upload")
    public BaseResponse<String> uploadFile(@RequestPart("file")MultipartFile multipartFile,
                                           UploadFileRequest uploadFileRequest, HttpServletRequest request) {
        String biz = uploadFileRequest.getBiz();
        FileUploadBizEnum fileUploadBizEnum = FileUploadBizEnum.getEnumByValue(biz);
        if (fileUploadBizEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        validFile(multipartFile,fileUploadBizEnum);
        User loginUser = userService.getLoginUser(request);
        //文件目录：根据业务、用户划分
        String uuid = RandomStringUtils.randomAlphabetic(8);
        String filename = uuid + "-" + multipartFile.getOriginalFilename();
        String filepath = String.format("/%s/%s/%s",fileUploadBizEnum.getValue(),loginUser.getId(),filename);
        File file = null;
        try {
            //上传文件
            file = File.createTempFile(filepath, null);
            multipartFile.transferTo(file);
            cosManager.putObject(filepath,file);
            //返回可访问地址
            return ResultUtils.success(FileConstant.COS_HOST + filepath);
        } catch (Exception e) {
            log.error("file upload error, filepath = " + filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件上传失败");
        } finally {
            boolean delete = file.delete();
            if (!delete) {
                log.error("file delete error, file = " + filepath);
            }
        }
    }

    /**
     * 校验文件格式
     * @param multipartFile
     * @param fileUploadBizEnum
     */
    private void validFile(MultipartFile multipartFile, FileUploadBizEnum fileUploadBizEnum) {
        //文件大小
        long fileSize = multipartFile.getSize();
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final long TWENTY_M = 1024L * 1024L * 20L;
        if (FileUploadBizEnum.USER_AVATAR.equals(fileUploadBizEnum)) {
            if (fileSize > TWENTY_M) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小不能超过 20M");
            }
            //允许上传的图片后缀
            List<String> fileSuffixs = Arrays.asList("jpeg", "jpg", "png", "svg", "webp");
            if (!fileSuffixs.contains(fileSuffix)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件类型错误");
            }
        }
    }
}
